package controllers

import (
	"chuanyou4/db"
	"chuanyou4/models"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"

	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

func (c *MainController) Get() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *MainController) Login() {
	c.TplName = "login.html"
}
func (c *MainController) Yanzhenglogin() {
	var sn = c.GetString("sn")
	var pswd = c.GetString("pswd")
	fmt.Println("收到的前端传过来的学号是：", sn, "密码是：", pswd)

	jiami := md5.New()
	jiami.Write([]byte(pswd))
	pswd = hex.EncodeToString(jiami.Sum(nil))
	var currentPerson models.Classmates
	db.DB.Raw("select * from chuanyou.classmates where sn=?", sn).Scan(&currentPerson)

	if currentPerson.Pswd == pswd {
		c.Data["json"] = currentPerson
	} else {
		c.Data["json"] = nil
	}
	c.ServeJSON()
}

func (c *MainController) Chongzhi() {
	c.Data["Name"] = "111111"
	c.Data["Sn"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *MainController) Chaxun() {
	var girls []*models.Classmates
	db.DB.Raw("select * from chuanyou.classmates").Scan(&girls)

	c.Data["Girls"] = girls

	c.TplName = "chaxun.html"

}

// 注册
func (c *MainController) Register() {
	c.TplName = "zhuce.html"
}

// 处理注册
func (c *MainController) Doregister() {
	var userinfo models.Classmates
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &userinfo)
	if err != nil {
		fmt.Println("接受用户注册信息报错：", err.Error())
		c.Data["json"] = err.Error()
		c.ServeJSON()
		return
	}
	jiami := md5.New()
	jiami.Write([]byte(userinfo.Pswd))
	userinfo.Pswd = hex.EncodeToString(jiami.Sum(nil))

	tx := db.DB.Create(userinfo)
	if tx.Error != nil {
		c.Data["json"] = "注册失败，原因是：" + tx.Error.Error()
		c.ServeJSON()
	}
	c.Data["json"] = "注册成功"
	c.ServeJSON()
}
